//
//  LKComposeViewController.swift
//  LKWeibo
//
//  Created by like on 16/8/17.
//  Copyright © 2016年 like. All rights reserved.
//

import UIKit
import SVProgressHUD

class LKComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        //添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeBottomView)
        composeTextView.addSubview(composePictureView)

        //添加约束
        composeTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        composeBottomView.snp_makeConstraints { (make) in
            make.leading.trailing.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        composePictureView.snp_makeConstraints { (make) in
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.centerX.equalTo(composeTextView)
        }
        
        //02实例化闭包
        composePictureView.closure = {[weak self]()->() in
            self?.selectImages()
        }
        
        
        //02 实例化闭包
        composeBottomView.closure = {[weak self] (type: LKComposeBottomViewType)->() in
            
            // 04
            switch type{
            case .Picture:
                print("图片")
                self?.selectImages()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("笑脸")
                self?.switchKeyboard()
            case .Add:
                print("+")
            }
        }
        //监听系统的
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LKComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
    }
    
    //实现监听的方法
    @objc private func keyboardWillChangeFrame(noti: NSNotification){
        // 动画时长
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
            return
        }
        
        guard let rect = noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
            return
        }
        // 获取到CGRect
        let newRect = rect.CGRectValue()
        
        composeBottomView.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(newRect.origin.y - SCREENH)
        }
        UIView.animateWithDuration(duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //设置左右item
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LKComposeViewController.cancelAction))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LKComposeViewController.sendAction))
        //一跳转界面，初始化的时候 设置不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
    }
    
    //左右item 的跳转方法
    @objc private func cancelAction(){
        
        self.dismissViewControllerAnimated(true) { 
            
        }
    }
    //监听的发送按钮的事件
    @objc private func sendAction(){
        
//        if composePictureView.imageList.count == 0 {
//            update()
//        }else {
//            upload()
//        }
      //三木运算符
        composePictureView.imageList.count == 0 ? update(): upload()
        
    }
    
    

    
    //懒加载title控件
    private lazy var titleView: UILabel = {
        let lab = UILabel()
        let name = LKUserAccountViewModel.sharedTools.userAccount!.screen_name!
        let str = "发微博\n\(name)"
        
        //创建渲染的范围
        
        let range = (str as NSString).rangeOfString(name)
        
        //初始化富文本
        let attr = NSMutableAttributedString(string: str)
        //创建富文本
        attr.addAttributes([NSForegroundColorAttributeName: appThemeColor,NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
        
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.attributedText = attr

        lab.sizeToFit()
        
        return lab
    }()
    
    
    //懒加载textView
    private lazy var composeTextView: LKComposeTextView = {
        let view = LKComposeTextView()
        view.delegate = self
        view.font = UIFont.systemFontOfSize(12)
        view.placeholder = "曾经沧海难为水...除却巫山不是云"
        view.alwaysBounceVertical = true
        return view
    }()
    
    //懒加载底部BOTTomview
    private lazy var composeBottomView: LKComposeBottomView = LKComposeBottomView()
    //图片
    private lazy var composePictureView: LKComposePictureView = LKComposePictureView()
    //自定义表情键盘
    private lazy var emoticonKeyboardView: LKEmoticonKeyboardView = LKEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 216))
    
}



extension LKComposeViewController{
    
    // 发布文字微博
    func update(){
        LKNetworkTools.sharedTools.composeUpdate(composeTextView.text, success: { (response) in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            //跳转到主页 并刷新数据
            NSNotificationCenter.defaultCenter().postNotificationName("reloadTableView", object: nil)
            self.cancelAction()
        }) { (error) in
            SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
    
    // 发布图片微博
    func upload(){
        LKNetworkTools.sharedTools.composeUpload(composeTextView.text, images: composePictureView.imageList, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            //跳转到主页 并刷新数据
            NSNotificationCenter.defaultCenter().postNotificationName("reloadTableView", object: nil)
            self.cancelAction()
        }) { (error) -> () in
            SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
    
    
    
}

//textview的 代理
extension LKComposeViewController:UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //取消编辑  两者功能一样
        self.composeTextView.endEditing(true)
        // 取消键盘第一响应
        //self.composeTextView.resignFirstResponder()
    }
}

//打开相册的方法
extension LKComposeViewController {
    //选择图片
    func selectImages(){
        let pickerVc = UIImagePickerController()
        pickerVc.delegate = self
        self.presentViewController(pickerVc, animated: true) {
        }
    }
    
    //切换键盘的方法
    func switchKeyboard(){
        //代表系统的键盘
        if  composeTextView.inputView == nil {
            
            composeTextView.inputView = emoticonKeyboardView
            composeBottomView.isEmoticon = true
            
        }else{ //代表表情键盘
            composeTextView.inputView = nil
            composeBottomView.isEmoticon = false
        }
        // 刷新
        composeTextView.reloadInputViews()
        //让键盘成为第一响应者
        composeTextView.becomeFirstResponder()
    }

 
}

//相册的代理方法
extension LKComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //取消
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        var image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        
//        composeTextView.backgroundColor = UIColor(patternImage: image)
        
        
        image = dealImageScale(image, width: 400)
        // 添加图片
        composePictureView.addImages(image)
        // 关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    //苹果建议不使用这个方法
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//    }
    
    /*
     - 用户上传头像 需要先压缩 然后上传
     - 服务器端得到后 它会通过他的渲染方式 保存一张上传的 和一张高清的 然后在你需要对应的图片的时候 给你提供对应的图片
     */
    // 图片压缩(等比例压缩)
    func dealImageScale(image: UIImage, width: CGFloat) -> UIImage{
        
        //如果你想压缩的图片 本身就很小了  不需要压缩了  直接return
        if image.size.width < width {
            return image
        }
        
        let height = image.size.height*width/image.size.width
        // 等比例后的高度
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        // 01 开启上下文
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
        // 02 把内容渲染到上下文中
        image.drawInRect(rect)
        // 03 从上下文获取内容
        let result = UIGraphicsGetImageFromCurrentImageContext()
        // 04 关闭上下文
        UIGraphicsEndImageContext()
        return result
    }
}